<template>
  <Dialog v-model="dialogVisible" title="批量分配" width="1200px">
    <el-form
      ref="formRef"
      :model="batchForm"
      :rules="batchRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <!-- 分配类型 -->
      <el-divider content-position="left">分配设置</el-divider>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="分配类型" prop="assignType">
            <el-radio-group v-model="batchForm.assignType">
              <el-radio value="evaluator">考评员分配</el-radio>
              <el-radio value="venue">考场分配</el-radio>
              <el-radio value="schedule">时间分配</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分配策略" prop="assignStrategy">
            <el-select v-model="batchForm.assignStrategy" placeholder="请选择分配策略">
              <el-option label="自动分配" value="auto" />
              <el-option label="手动指定" value="manual" />
              <el-option label="随机分配" value="random" />
              <el-option label="负载均衡" value="balance" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="评价计划" prop="planId">
            <el-select v-model="batchForm.planId" placeholder="请选择评价计划" @change="loadCandidates">
              <el-option label="2023年第四季度电工评价" value="1" />
              <el-option label="2023年第四季度焊工评价" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="目标职业" prop="professionId">
            <el-select v-model="batchForm.professionId" placeholder="请选择职业" clearable>
              <el-option label="全部职业" value="" />
              <el-option label="电工" value="1" />
              <el-option label="焊工" value="2" />
              <el-option label="车工" value="3" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <!-- 考评员分配设置 -->
      <div v-if="batchForm.assignType === 'evaluator'">
        <el-divider content-position="left">考评员分配设置</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="每组考评员数量" prop="evaluatorsPerGroup">
              <el-input-number
                v-model="batchForm.evaluatorsPerGroup"
                :min="1"
                :max="5"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="每组考生数量" prop="candidatesPerGroup">
              <el-input-number
                v-model="batchForm.candidatesPerGroup"
                :min="5"
                :max="50"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="考评员筛选条件">
          <el-checkbox-group v-model="batchForm.evaluatorFilters">
            <el-checkbox label="same_profession">同职业优先</el-checkbox>
            <el-checkbox label="high_level">高等级优先</el-checkbox>
            <el-checkbox label="experienced">经验丰富优先</el-checkbox>
            <el-checkbox label="available_time">时间可用</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </div>
      
      <!-- 考场分配设置 -->
      <div v-if="batchForm.assignType === 'venue'">
        <el-divider content-position="left">考场分配设置</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="每个考场容量" prop="venueCapacity">
              <el-input-number
                v-model="batchForm.venueCapacity"
                :min="10"
                :max="100"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考场数量限制" prop="maxVenues">
              <el-input-number
                v-model="batchForm.maxVenues"
                :min="1"
                :max="20"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="考场分配规则">
          <el-checkbox-group v-model="batchForm.venueRules">
            <el-checkbox label="same_profession">同职业同考场</el-checkbox>
            <el-checkbox label="same_level">同等级同考场</el-checkbox>
            <el-checkbox label="gender_balance">性别均衡</el-checkbox>
            <el-checkbox label="avoid_conflict">避免利害关系</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </div>
      
      <!-- 时间分配设置 -->
      <div v-if="batchForm.assignType === 'schedule'">
        <el-divider content-position="left">时间分配设置</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="考试开始时间" prop="examStartTime">
              <el-date-picker
                v-model="batchForm.examStartTime"
                type="datetime"
                placeholder="选择开始时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="考试时长" prop="examDuration">
              <el-input-number
                v-model="batchForm.examDuration"
                :min="60"
                :max="480"
                style="width: 100%"
              />
              <span style="margin-left: 10px;">分钟</span>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="场次间隔" prop="sessionInterval">
              <el-input-number
                v-model="batchForm.sessionInterval"
                :min="15"
                :max="120"
                style="width: 100%"
              />
              <span style="margin-left: 10px;">分钟</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="每场次人数" prop="candidatesPerSession">
              <el-input-number
                v-model="batchForm.candidatesPerSession"
                :min="10"
                :max="50"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      
      <!-- 高级设置 -->
      <el-divider content-position="left">高级设置</el-divider>
      <el-form-item label="分配约束条件">
        <el-checkbox-group v-model="batchForm.constraints">
          <el-checkbox label="geographic">地理位置约束</el-checkbox>
          <el-checkbox label="relationship">关系回避约束</el-checkbox>
          <el-checkbox label="workload">工作量平衡约束</el-checkbox>
          <el-checkbox label="preference">个人偏好约束</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      
      <el-form-item label="特殊处理">
        <el-checkbox-group v-model="batchForm.specialHandling">
          <el-checkbox label="vip_priority">VIP考生优先</el-checkbox>
          <el-checkbox label="disability_support">残障考生支持</el-checkbox>
          <el-checkbox label="makeup_exam">补考考生处理</el-checkbox>
          <el-checkbox label="emergency_reserve">应急预留</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      
      <el-form-item label="分配备注" prop="assignRemark">
        <el-input
          v-model="batchForm.assignRemark"
          type="textarea"
          :rows="3"
          placeholder="请输入分配说明和备注"
        />
      </el-form-item>
    </el-form>
    
    <!-- 候选人列表 -->
    <el-divider content-position="left">待分配人员</el-divider>
    <div style="margin-bottom: 15px;">
      <el-space>
        <el-button type="success" @click="selectAll">全选</el-button>
        <el-button @click="clearSelection">清空选择</el-button>
        <el-button type="primary" @click="previewAssignment" :disabled="selectedCandidates.length === 0">
          预览分配 ({{ selectedCandidates.length }})
        </el-button>
      </el-space>
    </div>
    
    <el-table 
      ref="tableRef"
      :data="candidateList" 
      border 
      style="width: 100%"
      @selection-change="handleSelectionChange"
      max-height="300"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="candidateName" label="考生姓名" width="120" />
      <el-table-column prop="idCard" label="身份证号" width="180" />
      <el-table-column prop="professionName" label="申报职业" width="120" />
      <el-table-column prop="skillLevel" label="申报等级" width="100">
        <template #default="{ row }">
          {{ getLevelName(row.skillLevel) }}
        </template>
      </el-table-column>
      <el-table-column prop="currentAssignment" label="当前分配" width="150" />
      <el-table-column prop="assignStatus" label="分配状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getAssignStatusColor(row.assignStatus)">
            {{ getAssignStatusName(row.assignStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="specialNotes" label="特殊说明" />
    </el-table>
    
    <!-- 分配预览 -->
    <el-dialog v-model="previewDialogVisible" title="分配预览" width="1000px">
      <div v-if="assignmentPreview.length > 0">
        <el-alert
          :title="`分配方案：共 ${assignmentPreview.length} 个分组，涉及 ${selectedCandidates.length} 名考生`"
          type="info"
          :closable="false"
          style="margin-bottom: 20px;"
        />
        
        <el-collapse v-model="activeGroups">
          <el-collapse-item
            v-for="(group, index) in assignmentPreview"
            :key="index"
            :title="`第 ${index + 1} 组 (${group.members.length} 人)`"
            :name="index"
          >
            <el-descriptions :column="2" border style="margin-bottom: 15px;">
              <el-descriptions-item label="分组名称">{{ group.groupName }}</el-descriptions-item>
              <el-descriptions-item label="分配类型">{{ getAssignTypeName(group.assignType) }}</el-descriptions-item>
              <el-descriptions-item label="负责人">{{ group.supervisor || '-' }}</el-descriptions-item>
              <el-descriptions-item label="执行时间">{{ group.scheduleTime || '-' }}</el-descriptions-item>
            </el-descriptions>
            
            <el-table :data="group.members" border size="small">
              <el-table-column prop="candidateName" label="考生姓名" width="120" />
              <el-table-column prop="professionName" label="职业" width="100" />
              <el-table-column prop="skillLevel" label="等级" width="80">
                <template #default="{ row }">
                  {{ getLevelName(row.skillLevel) }}
                </template>
              </el-table-column>
              <el-table-column prop="role" label="角色" width="100" />
              <el-table-column prop="assignedResource" label="分配资源" />
            </el-table>
          </el-collapse-item>
        </el-collapse>
      </div>
      
      <template #footer>
        <el-button @click="previewDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="confirmAssignment">确认分配</el-button>
      </template>
    </el-dialog>
    
    <template #footer>
      <el-button @click="executeAssignment" type="primary" :loading="formLoading">
        执行分配
      </el-button>
      <el-button @click="exportAssignment" type="success">
        导出分配表
      </el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'

const emit = defineEmits(['success'])
const dialogVisible = ref(false)
const formLoading = ref(false)
const previewDialogVisible = ref(false)
const formRef = ref()
const tableRef = ref()

const selectedCandidates = ref([])
const activeGroups = ref([0])
const assignmentPreview = ref([])

const batchForm = ref({
  assignType: 'evaluator',
  assignStrategy: 'auto',
  planId: '',
  professionId: '',
  evaluatorsPerGroup: 2,
  candidatesPerGroup: 20,
  evaluatorFilters: [] as string[],
  venueCapacity: 30,
  maxVenues: 5,
  venueRules: [] as string[],
  examStartTime: '',
  examDuration: 180,
  sessionInterval: 30,
  candidatesPerSession: 25,
  constraints: [] as string[],
  specialHandling: [] as string[],
  assignRemark: ''
})

const batchRules = ref({
  assignType: [{ required: true, message: '请选择分配类型', trigger: 'change' }],
  assignStrategy: [{ required: true, message: '请选择分配策略', trigger: 'change' }],
  planId: [{ required: true, message: '请选择评价计划', trigger: 'change' }]
})

const candidateList = ref([
  {
    id: 1,
    candidateName: '张三',
    idCard: '123456789012345678',
    professionName: '电工',
    skillLevel: 3,
    currentAssignment: '未分配',
    assignStatus: 'unassigned',
    specialNotes: ''
  },
  {
    id: 2,
    candidateName: '李四',
    idCard: '123456789012345679',
    professionName: '焊工',
    skillLevel: 2,
    currentAssignment: '考评组A',
    assignStatus: 'assigned',
    specialNotes: 'VIP考生'
  },
  {
    id: 3,
    candidateName: '王五',
    idCard: '123456789012345680',
    professionName: '车工',
    skillLevel: 4,
    currentAssignment: '未分配',
    assignStatus: 'unassigned',
    specialNotes: '残障考生'
  }
])

const getLevelName = (level: number) => {
  const levelMap = { 1: '初级', 2: '中级', 3: '高级', 4: '技师', 5: '高级技师' }
  return levelMap[level] || '-'
}

const getAssignStatusName = (status: string) => {
  const statusMap = {
    'unassigned': '未分配',
    'assigned': '已分配',
    'locked': '已锁定',
    'conflict': '存在冲突'
  }
  return statusMap[status] || status
}

const getAssignStatusColor = (status: string) => {
  const colorMap = {
    'unassigned': 'warning',
    'assigned': 'success',
    'locked': 'info',
    'conflict': 'danger'
  }
  return colorMap[status] || 'info'
}

const getAssignTypeName = (type: string) => {
  const typeMap = {
    'evaluator': '考评员分配',
    'venue': '考场分配',
    'schedule': '时间分配'
  }
  return typeMap[type] || type
}

const handleSelectionChange = (selection: any[]) => {
  selectedCandidates.value = selection
}

const selectAll = () => {
  tableRef.value?.toggleAllSelection()
}

const clearSelection = () => {
  tableRef.value?.clearSelection()
}

const loadCandidates = () => {
  // TODO: 根据计划加载考生
  console.log('加载考生列表', batchForm.value.planId)
}

const previewAssignment = () => {
  if (selectedCandidates.value.length === 0) {
    ElMessage.warning('请先选择要分配的考生')
    return
  }
  
  // 生成分配预览
  generateAssignmentPreview()
  previewDialogVisible.value = true
}

const generateAssignmentPreview = () => {
  const groupSize = batchForm.value.assignType === 'evaluator' 
    ? batchForm.value.candidatesPerGroup 
    : batchForm.value.assignType === 'venue'
    ? batchForm.value.venueCapacity
    : batchForm.value.candidatesPerSession
  
  const groups = []
  const candidates = [...selectedCandidates.value]
  
  let groupIndex = 0
  while (candidates.length > 0) {
    const groupMembers = candidates.splice(0, groupSize)
    groups.push({
      groupName: `${getAssignTypeName(batchForm.value.assignType)} ${groupIndex + 1}`,
      assignType: batchForm.value.assignType,
      supervisor: `负责人${groupIndex + 1}`,
      scheduleTime: batchForm.value.examStartTime || '待定',
      members: groupMembers.map(member => ({
        ...member,
        role: '考生',
        assignedResource: `资源${groupIndex + 1}`
      }))
    })
    groupIndex++
  }
  
  assignmentPreview.value = groups
  activeGroups.value = groups.map((_, index) => index)
}

const confirmAssignment = () => {
  previewDialogVisible.value = false
  executeAssignment()
}

const executeAssignment = async () => {
  if (selectedCandidates.value.length === 0) {
    ElMessage.warning('请先选择要分配的考生')
    return
  }
  
  const elForm = formRef.value
  if (!elForm) return
  const valid = await elForm.validate()
  if (!valid) return
  
  formLoading.value = true
  try {
    const assignmentData = {
      assignConfig: batchForm.value,
      candidateIds: selectedCandidates.value.map(c => c.id),
      assignmentGroups: assignmentPreview.value
    }
    
    // TODO: 执行批量分配
    console.log('执行批量分配:', assignmentData)
    
    // 更新本地状态
    selectedCandidates.value.forEach(candidate => {
      const index = candidateList.value.findIndex(c => c.id === candidate.id)
      if (index > -1) {
        candidateList.value[index].assignStatus = 'assigned'
        candidateList.value[index].currentAssignment = '批量分配完成'
      }
    })
    
    dialogVisible.value = false
    emit('success')
    ElMessage.success(`成功分配 ${selectedCandidates.value.length} 名考生`)
  } finally {
    formLoading.value = false
  }
}

const exportAssignment = () => {
  if (assignmentPreview.value.length === 0) {
    ElMessage.warning('请先预览分配方案')
    return
  }
  
  // TODO: 导出分配表
  ElMessage.info('分配表导出功能开发中...')
}

const resetForm = () => {
  batchForm.value = {
    assignType: 'evaluator',
    assignStrategy: 'auto',
    planId: '',
    professionId: '',
    evaluatorsPerGroup: 2,
    candidatesPerGroup: 20,
    evaluatorFilters: [],
    venueCapacity: 30,
    maxVenues: 5,
    venueRules: [],
    examStartTime: '',
    examDuration: 180,
    sessionInterval: 30,
    candidatesPerSession: 25,
    constraints: [],
    specialHandling: [],
    assignRemark: ''
  }
  
  selectedCandidates.value = []
  assignmentPreview.value = []
  
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const open = () => {
  dialogVisible.value = true
  resetForm()
}

defineExpose({ open })
</script>
